/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { spawn } from 'child_process'
import type { ChildProcess } from 'child_process'
import type { IpcMain } from 'electron'
import { EventEmitter } from 'events'
import * as fs from 'fs'
import airspaceSlice from '../../resources/airspace-slice/airspace-slice.exe?asset&asarUnpack'
import logger from 'electron-log'

/**
 * 外部进程状态枚举
 */
export type ProcessState = 'IDLE' | 'RUNNING' | 'CRASHED' | 'EXITED'

export const ProcessState = {
  IDLE: 'IDLE',
  RUNNING: 'RUNNING',
  CRASHED: 'CRASHED',
  EXITED: 'EXITED'
} as const

/**
 * 外部进程处理器
 */
export class ProcessHandler extends EventEmitter {
  private process: ChildProcess | null = null
  private state: ProcessState = ProcessState.IDLE
  private executable: string

  constructor(executablePath: string) {
    super()
    this.executable = executablePath
  }

  /**
   * 启动外部进程
   * @param args 命令行参数
   * @returns 是否成功启动
   */
  public start(args: string[] = []): boolean {
    if (this.process) {
      logger.warn('进程已在运行中')
      return false
    }

    try {
      this.process = spawn(this.executable, args, {
        stdio: ['pipe', 'pipe', 'pipe'],
        shell: false
      })

      this.state = ProcessState.RUNNING

      // 监听进程退出
      this.process.on('exit', (code, signal) => {
        const normalExit = code === 0
        this.state = normalExit ? ProcessState.EXITED : ProcessState.CRASHED
        this.emit('exit', { code, signal, normalExit })
        this.process = null
      })

      // 监听进程错误
      this.process.on('error', (error) => {
        this.state = ProcessState.CRASHED
        this.emit('error', error)
      })

      // 监听标准输出
      this.process.stdout?.on('data', (data) => {
        this.emit('stdout', data.toString())
      })

      // 监听标准错误
      this.process.stderr?.on('data', (data) => {
        this.emit('stderr', data.toString())
      })

      return true
    } catch (error) {
      logger.error('启动进程失败:', error)
      this.state = ProcessState.CRASHED
      this.emit('error', error)
      return false
    }
  }

  /**
   * 停止外部进程
   */
  public stop(): boolean {
    if (!this.process) {
      logger.warn('没有正在运行的进程')
      return false
    }

    try {
      const result = this.process.kill()
      return result
    } catch (error) {
      logger.error('停止进程失败:', error)
      return false
    }
  }

  /**
   * 获取当前进程状态
   */
  public getState(): ProcessState {
    return this.state
  }

  /**
   * 检查进程是否在运行
   */
  public isRunning(): boolean {
    return this.state === ProcessState.RUNNING && this.process !== null
  }
}

/**
 * 专门用于处理airspace-slice.exe的处理器
 */
export class AirspaceSliceProcessor extends EventEmitter {
  private processHandler: ProcessHandler
  private stateWatcher: NodeJS.Timeout | null = null
  private lastState: ProcessState = ProcessState.IDLE
  private executablePath: string

  constructor() {
    super()

    // 改进路径解析逻辑，优先使用传入的路径，其次使用app.getPath('exe')相对路径，最后尝试相对于当前目录

    this.executablePath = airspaceSlice
    // 检查文件是否存在
    if (!fs.existsSync(this.executablePath)) {
      logger.error(`警告: airspace-slice.exe 文件不存在: ${this.executablePath}`)
    }

    // 创建进程处理器
    this.processHandler = new ProcessHandler(this.executablePath)

    // 添加事件监听
    this.processHandler.on('exit', (data) => this.handleExit(data))
    this.processHandler.on('error', (error) => this.handleError(error))
    this.processHandler.on('stdout', (data) => this.handleStdout(data))
    this.processHandler.on('stderr', (data) => this.handleStderr(data))

    // 初始化最后状态
    this.lastState = this.processHandler.getState()
  }

  /**
   * 启动airspace-slice程序
   * @param args 传递给程序的命令行参数
   */
  public start(args: string[] = []): boolean {
    // 启动前先检查文件是否存在
    if (!fs.existsSync(this.executablePath)) {
      logger.error(`错误: 无法启动airspace-slice.exe, 文件不存在: ${this.executablePath}`)
      return false
    }

    logger.info(`start airspace-slice: ${this.executablePath}  ${args.join(' ')}`)
    return this.processHandler.start(args)
  }

  /**
   * 停止airspace-slice程序
   */
  public stop(): boolean {
    return this.processHandler.stop()
  }

  /**
   * 获取进程状态
   */
  public getState(): ProcessState {
    return this.processHandler.getState()
  }

  /**
   * 启动进程状态监视器
   * @param interval 监视间隔，默认1000毫秒
   * @param autoRestart 是否在崩溃时自动重启，默认false
   * @returns 是否成功启动监视器
   */
  public startStateWatcher(interval: number = 1000, autoRestart: boolean = false): boolean {
    // 如果已经在监视，先停止现有监视器
    this.stopStateWatcher()

    this.stateWatcher = setInterval(() => {
      const currentState = this.processHandler.getState()

      // 检测状态变化
      if (currentState !== this.lastState) {
        this.emit('stateChanged', {
          previousState: this.lastState,
          currentState: currentState
        })
        this.lastState = currentState
      }

      // 如果进程崩溃且配置了自动重启
      if (autoRestart && currentState === ProcessState.CRASHED) {
        logger.info('The process crashed. Try to restart it automatically.')
      }
    }, interval)

    return true
  }

  /**
   * 停止进程状态监视器
   * @returns 是否成功停止监视器
   */
  public stopStateWatcher(): boolean {
    if (this.stateWatcher) {
      clearInterval(this.stateWatcher)
      this.stateWatcher = null
      return true
    }
    return false
  }

  /**
   * 检查监视器是否在运行
   */
  public isWatcherRunning(): boolean {
    return this.stateWatcher !== null
  }

  /**
   * 处理进程退出事件
   */
  private handleExit(data: {
    code: number | null
    signal: NodeJS.Signals | null
    normalExit: boolean
  }) {
    logger.info(`airspace-slice process exit: exit code: ${data.code}, single: ${data.signal}`)
    // 这里可以添加重启逻辑或其他处理
  }

  /**
   * 处理进程错误事件
   */
  private handleError(error: Error) {
    logger.error('airspace-slice process error:', error)
  }

  /**
   * 处理标准输出
   */
  private handleStdout(data: string) {
    logger.info(`airspace-slice output: ${data.trim()}`)
  }

  /**
   * 处理标准错误
   */
  private handleStderr(data: string) {
    logger.error(`airspace-slice log : ${data.trim()}`)
  }
}

export const initProcess = async (ipcMain: IpcMain) => {
  // 创建进程处理器实例
  const processHandler = new AirspaceSliceProcessor()
  // Register IPC handler
  ipcMain.handle('window-start-process', async (event, arg: string) => {
    // 读取配置文件
    const args = [arg] // 替换为实际参数
    const result = processHandler.start(args)

    if (result) {
      logger.info('process started successfully !')
      // 设置状态变化事件监听器，将状态变化发送到渲染进程
      processHandler.on('stateChanged', (stateData) => {
        const state = stateData.currentState
        event.sender.send('process-state-changed', state)
      })

      return processHandler.startStateWatcher(1000, false)
    }

    return result
  })

  // 处理进程启动
  ipcMain.handle('window-stop-process', async () => {
    const result = processHandler.stop()
    return result
  })

  // 处理进程状态
  ipcMain.handle('window-get-process-state', async () => {
    const state = processHandler.getState()
    return state
  })

  // 停止进程状态监视器
  ipcMain.handle('window-stop-state-watcher', async () => {
    return processHandler.stopStateWatcher()
  })

  // 查询监视器是否在运行
  ipcMain.handle('window-is-watcher-running', async () => {
    return processHandler.isWatcherRunning()
  })

  // 启动默认监视器（立即生效）
  processHandler.startStateWatcher(1000, true) // 每秒监视一次，自动重启崩溃的进程
}
